package com.bezkoder.springjwt.controllers;

import com.bezkoder.springjwt.models.Order;
import com.bezkoder.springjwt.repository.OrderRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/orders")
public class OrderController {
    @Autowired
    private OrderRepository orderRepository;

    @GetMapping("")
    @PreAuthorize("hasRole('USER') or hasRole('ADMIN')")
    public List<Order> getOrders() {
        return orderRepository.findAll();
    }

    @GetMapping("/{id}")
    @PreAuthorize("hasRole('USER') or hasRole('ADMIN')")
    public Order getOrderById(@PathVariable Integer id) {
        return orderRepository.findById(id).orElse(null);
    }

    @PostMapping("")
    @PreAuthorize("hasRole('USER') or hasRole('ADMIN')")
    public Order addOrder(@RequestBody Order order) {
        return orderRepository.save(order);
    }

    @PutMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN')")
    public Order updateOrder(@PathVariable Integer id,
                             @RequestBody Order order) {
        Order oldOrder = orderRepository.findById(id).orElse(null);
        if (oldOrder != null) {
            oldOrder.setName(order.getName());
            oldOrder.setAmount(order.getAmount());
            oldOrder.setState(order.getState());
            return orderRepository.save(oldOrder);
        } else {
            return null;
        }
    }

    @DeleteMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN')")
    public void deleteOrder(@PathVariable Integer id) {
        orderRepository.deleteById(id);
    }
}